import os
import sys
import base64
from pathlib import Path

def image_to_base64(image_path):
    """将图片转换为base64字符串"""
    with open(image_path, 'rb') as image_file:
        encoded_string = base64.b64encode(image_file.read()).decode('utf-8')
        # 根据文件扩展名添加适当的前缀
        ext = image_path.suffix.lower()
        if ext == '.png':
            return f'data:image/png;base64,{encoded_string}'
        elif ext in ['.jpg', '.jpeg']:
            return f'data:image/jpeg;base64,{encoded_string}'
        else:
            raise ValueError(f'不支持的图片格式: {ext}')

def process_image_files(directory_path):
    """处理图片文件"""
    directory_path = Path(directory_path).resolve()
    print(f"处理目录: {directory_path}")
    
    # 映射文件名到变量名
    name_mapping = {
        'logo爱-红': 'redLogo',
        '爱-红': 'redLogo1',
        'logo爱-白': 'whiteLogo',
        '爱-白': 'whiteLogo1'
    }
    
    results = {}
    # 支持的图片格式
    image_extensions = ['.png', '.jpg', '.jpeg']
    
    for file_path in directory_path.glob('*'):
        if file_path.suffix.lower() in image_extensions:
            stem = file_path.stem
            if stem in name_mapping:
                try:
                    print(f"\n处理文件: {file_path.name}")
                    base64_string = image_to_base64(file_path)
                    results[name_mapping[stem]] = base64_string
                    print(f'处理完成: {file_path.name}')
                except Exception as e:
                    print(f'处理 {file_path.name} 时出错: {str(e)}')
    
    return results

def generate_typescript_file(results, output_file):
    """生成 TypeScript 文件"""
    # 确保输出目录存在
    output_dir = os.path.dirname(output_file)
    os.makedirs(output_dir, exist_ok=True)
    
    content = """// Base64 编码的图片
export const images = {
"""
    
    for name, base64_str in results.items():
        content += f"    {name}: \"{base64_str}\",\n"
    
    content += "};\n"
    
    with open(output_file, 'w', encoding='utf-8') as f:
        f.write(content)
    
    print(f"已生成 TypeScript 文件: {output_file}")

if __name__ == '__main__':
    # 获取项目根目录
    root_dir = os.path.dirname(os.path.abspath(__file__))
    # 设置目标目录为 public/img/logo
    target_dir = os.path.join(root_dir, 'public', 'img', 'logo')
    print(f'开始处理图片文件...\n目标目录: {target_dir}')
    
    # 处理图片文件
    results = process_image_files(target_dir)
    
    # 设置输出文件路径
    output_file = os.path.join(root_dir, 'src', 'assets', 'base64Images.ts')
    
    # 生成 TypeScript 文件
    generate_typescript_file(results, output_file)
    
    print('处理完成！') 